package com.tchcn.supermarket.ui.activity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.tchcn.library.dao.LocalUserModelDao;
import com.tchcn.library.dao.MenuModelDao;
import com.tchcn.library.dao.StoreBeanDao;
import com.tchcn.library.model.MenuModel;
import com.tchcn.library.model.StoreBean;
import com.tchcn.library.model.UserInfoModel;
import com.tchcn.supermarket.R;
import com.tchcn.supermarket.base.BaseRecyclerAdapter;
import com.tchcn.supermarket.base.SBaseActivity;
import com.tchcn.supermarket.ui.fragment.BackstageGoodsManageFragment;
import com.tchcn.supermarket.ui.fragment.CashPermissionFragment;
import com.tchcn.supermarket.ui.fragment.CashierHomeFragment;
import com.tchcn.supermarket.ui.fragment.CommodityStorageFragment;
import com.tchcn.supermarket.ui.fragment.OperationRecordFragment;
import com.tchcn.supermarket.ui.fragment.UserManageFragment;
import com.tchcn.supermarket.utils.AnimationUtil;
import com.tchcn.supermarket.utils.GlideUtil;
import com.tchcn.supermarket.utils.KeyboardUtil;
import com.tchcn.supermarket.utils.SDToast;
import com.tchcn.supermarket.utils.ViewBinder;

import java.util.ArrayList;
import java.util.List;

/**
 *  收银台主界面
 *  @author humu 2018/4/28.
 * */
public class CashierHomeActivity extends SBaseActivity {
    
    private Fragment nowFragment;

    //门店
    private TextView tv_location;
    private SimpleDraweeView sdv;
    //收银台
    private RelativeLayout rl_cashier;
    private View view_cashier_selected;
    private TextView tv_cashier;
    //库存查询
    private RelativeLayout rl_inventory_inquiry;
    private View view_ii_selected;
    private TextView tv_ii;
    private ImageView iv_ii_arrow;
    private LinearLayout ll_ii_menus;
    private RelativeLayout rl_cs;
    private View view_cs;
    private TextView tv_cs;
    private RelativeLayout rl_or;
    private View view_or;
    private TextView tv_or;
    private View view_back_selected;
    private TextView tv_back_manage;
    private ImageView iv_bm_arrow;
    //后台管理
    private RelativeLayout rl_backstage_management;
    //后台管理子菜单
    private LinearLayout ll_bm_menus;
    //商品管理
    private RelativeLayout rl_gm;
    private View view_gm;
    private TextView tv_gm;
    //用户管理
    private RelativeLayout rl_um;
    private View view_um;
    private TextView tv_um;
    //会员管理
    private RelativeLayout rl_mm;
    private View view_mm;
    private TextView tv_mm;
    //商家资料
    private RelativeLayout rl_bi;
    private View view_bi;
    private TextView tv_bi;
    private TextView tv_user_name;
    private TextView tv_user_type;
    //收银权限
    private RelativeLayout rl_cash_permission;
    private View view_cp;
    private TextView tv_cp;
    private LinearLayout ll_change_location;
    private View view_mask;
    private RecyclerView rv_popup;
    private RelativeLayout rl_popup_items;

    private int menu_index = 1; //1收银台，2库存查询，3商品入库，4操作记录

    private String locationId = ""; //门店id
    private String supplierId = ""; //商户id

    private boolean pCashier = false;
    private boolean pStorage = false;
    private boolean pOperateRecord = false;
    private boolean pGoodManage = false;
    private boolean pUserManage = false;
    private boolean pCashPermission = false;
    private StoreBeanAdapter storeBeanAdapter;

    @Override
    protected void initView() {
        initUI();
        initFragment();
        initLocation();
        initUser();
        updatePermissions();
    }

    private void initUser() {
        UserInfoModel userInfoModel = LocalUserModelDao.queryModel();
        if(userInfoModel != null){
            String name = userInfoModel.getName();
            ViewBinder.setTextView(tv_user_name,name);
            GlideUtil.load(context,userInfoModel.getImg(),sdv);
        }
    }

    public void updatePermissions(){
        List<MenuModel> menuModels = MenuModelDao.queryModel();
        if(menuModels != null && menuModels.size() > 0){
            for (MenuModel model : menuModels){
                switch (model.getMenu_name()){
                    case "收银台":
                        pCashier = true;
                        break;
                    case "商品入库":
                        pStorage = true;
                        break;
                    case "操作记录":
                        pOperateRecord = true;
                        break;
                    case "商品管理":
                        pGoodManage = true;
                        break;
                    case "用户管理":
                        pUserManage = true;
                        break;
                    case "收银权限":
                        pCashPermission = true;
                        break;
                }
            }
        }
    }

    //初始化门店
    private void initLocation() {
        StoreBean storeBean = StoreBeanDao.queryDefaultModel();
        locationId = storeBean.getId()+"";
        supplierId = storeBean.getSupplier_id()+"";
        ViewBinder.setTextView(tv_location,storeBean.getLocation_name());
        storeBeanAdapter = new StoreBeanAdapter();
        storeBeanAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<StoreBean>() {
            @Override
            public void onItemClick(View covertView, int position, StoreBean data) {
                ViewBinder.setTextView(tv_location,data.getLocation_name());
                locationId = data.getId()+"";
                hideItemsPopup();
            }
        });
    }

    //门店选择
    class StoreBeanAdapter extends BaseRecyclerAdapter<StoreBean>{

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.sitem_popup_item;
        }

        @Override
        public void setUpData(CommonHolder holder, int position, int viewType, StoreBean data) {
            TextView tv_item_name = getView(holder,R.id.tv_item_name);
            ImageView iv_checked = getView(holder,R.id.iv_checked);
            ViewBinder.setTextView(tv_item_name,data.getLocation_name());
            if(tv_location.getText().toString().equals(data.getLocation_name())){
                tv_item_name.setTextColor(getResources().getColor(R.color.main_blue));
                iv_checked.setVisibility(View.VISIBLE);
            }else{
                tv_item_name.setTextColor(getResources().getColor(R.color.six_six));
                iv_checked.setVisibility(View.GONE);
            }
        }
    }

    private void initUI() {
        tv_location = find(R.id.tv_location);
        tv_user_name = find(R.id.tv_user_name);
        tv_user_type = find(R.id.tv_user_type);
        sdv = find(R.id.sdv);
        rl_cashier = find(R.id.rl_cashier);
        view_cashier_selected = find(R.id.view_cashier_selected);
        rl_inventory_inquiry = find(R.id.rl_inventory_inquiry);
        rl_backstage_management = find(R.id.rl_backstage_management);
        rl_backstage_management.setOnClickListener(this);
        ll_ii_menus = find(R.id.ll_ii_menus);
        tv_cashier = find(R.id.tv_cashier);
        view_ii_selected = find(R.id.view_ii_selected);
        tv_ii = find(R.id.tv_ii);
        view_cs = find(R.id.view_cs);
        tv_cs = find(R.id.tv_cs);
        view_or = find(R.id.view_or);
        tv_or = find(R.id.tv_or);
        rl_cs = find(R.id.rl_cs);
        rl_or = find(R.id.rl_or);
        iv_ii_arrow = find(R.id.iv_ii_arrow);
        view_back_selected = find(R.id.view_back_selected);
        tv_back_manage = find(R.id.tv_back_manage);
        ll_bm_menus = find(R.id.ll_bm_menus);
        iv_bm_arrow = find(R.id.iv_bm_arrow);
        rl_gm = find(R.id.rl_gm);
        rl_gm.setOnClickListener(this);
        view_gm = find(R.id.view_gm);
        tv_gm = find(R.id.tv_gm);
        rl_um = find(R.id.rl_um);
        rl_um.setOnClickListener(this);
        view_um = find(R.id.view_um);
        tv_um = find(R.id.tv_um);
        rl_mm = find(R.id.rl_mm);
        rl_mm.setOnClickListener(this);
        view_mm = find(R.id.view_mm);
        tv_mm = find(R.id.tv_mm);
        rl_bi = find(R.id.rl_bi);
        rl_bi.setOnClickListener(this);
        view_bi = find(R.id.view_bi);
        tv_bi = find(R.id.tv_bi);
        rl_cashier.setOnClickListener(this);
        rl_inventory_inquiry.setOnClickListener(this);
        rl_cs.setOnClickListener(this);
        rl_or.setOnClickListener(this);
        TextView tv_loginout = find(R.id.tv_loginout);
        tv_loginout.setOnClickListener(this);
        rl_cash_permission = find(R.id.rl_cash_permission);
        rl_cash_permission.setOnClickListener(this);
        view_cp = find(R.id.view_cp);
        tv_cp = find(R.id.tv_cp);
        ll_change_location = find(R.id.ll_change_location);
        ll_change_location.setOnClickListener(this);
        view_mask = find(R.id.view_mask);
        view_mask.setOnClickListener(this);
        rv_popup = find(R.id.rv_popup);
        rv_popup.setLayoutManager(new LinearLayoutManager(context));
        rl_popup_items = find(R.id.rl_popup_items);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.sactivity_cashier_home;
    }

    //左侧菜单的切换
    private void changeFragment(Fragment fromFragment, Fragment toFragment) {

        if (nowFragment != null && nowFragment != toFragment) {
            nowFragment = toFragment;
        }
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        if (toFragment.isAdded() == false) {
            ft.hide(fromFragment).add(R.id.frame_main, toFragment).commit();
        } else {
            ft.hide(fromFragment).show(toFragment).commit();
        }

    }

    private void resetGmMenus(){
        view_mm.setBackgroundResource(R.drawable.sshape_menu_point_normal);
        tv_mm.setTextColor(getResources().getColor(R.color.six_six));
        view_bi.setBackgroundResource(R.drawable.sshape_menu_point_normal);
        tv_bi.setTextColor(getResources().getColor(R.color.six_six));
        view_um.setBackgroundResource(R.drawable.sshape_menu_point_normal);
        tv_um.setTextColor(getResources().getColor(R.color.six_six));
        view_gm.setBackgroundResource(R.drawable.sshape_menu_point_normal);
        tv_gm.setTextColor(getResources().getColor(R.color.six_six));
        view_cp.setBackgroundResource(R.drawable.sshape_menu_point_normal);
        tv_cp.setTextColor(getResources().getColor(R.color.six_six));
    }

    private void choseGmMenu(int index){
        resetGmMenus();
        switch (index){
            case 1:
                view_gm.setBackgroundResource(R.drawable.sshape_menu_point_selected);
                tv_gm.setTextColor(getResources().getColor(R.color.main_blue));
                break;
            case 2:
                view_um.setBackgroundResource(R.drawable.sshape_menu_point_selected);
                tv_um.setTextColor(getResources().getColor(R.color.main_blue));
                break;
            case 3:
                view_mm.setBackgroundResource(R.drawable.sshape_menu_point_selected);
                tv_mm.setTextColor(getResources().getColor(R.color.main_blue));
                break;
            case 4:
                view_bi.setBackgroundResource(R.drawable.sshape_menu_point_selected);
                tv_bi.setTextColor(getResources().getColor(R.color.main_blue));
                break;
            case 5:
                view_cp.setBackgroundResource(R.drawable.sshape_menu_point_selected);
                tv_cp.setTextColor(getResources().getColor(R.color.main_blue));
                break;
        }
    }

    private void changeMenuState(int index){
        switch (index){
            case 1: //收银台
                if(menu_index != 1){
                    rl_cashier.setBackgroundColor(getResources().getColor(R.color.three_f5));
                    view_cashier_selected.setVisibility(View.VISIBLE);
                    tv_cashier.setTextColor(getResources().getColor(R.color.main_blue));
                    rl_inventory_inquiry.setBackgroundColor(getResources().getColor(R.color.white));
                    view_ii_selected.setVisibility(View.GONE);
                    tv_ii.setTextColor(getResources().getColor(R.color.six_six));
                    tv_cs.setTextColor(getResources().getColor(R.color.six_six));
                    view_cs.setBackgroundResource(R.drawable.sshape_menu_point_normal);
                    tv_or.setTextColor(getResources().getColor(R.color.six_six));
                    view_or.setBackgroundResource(R.drawable.sshape_menu_point_normal);
                    ll_ii_menus.setVisibility(View.GONE);
                    rl_backstage_management.setBackgroundColor(getResources().getColor(R.color.white));
                    view_back_selected.setVisibility(View.GONE);
                    tv_back_manage.setTextColor(getResources().getColor(R.color.six_six));
                    ll_bm_menus.setVisibility(View.GONE);
                    if(menu_index == 5){
                        Animation rotate = AnimationUtils.loadAnimation(activity, R.anim.sanim_arrow_back);//创建动画
                        rotate.setInterpolator(new LinearInterpolator());//设置为线性旋转
                        rotate.setFillAfter(true);
                        iv_bm_arrow.startAnimation(rotate);
                    }else if(menu_index == 2 || menu_index == 3 || menu_index == 4){
                        Animation rotate = AnimationUtils.loadAnimation(activity, R.anim.sanim_arrow_back);//创建动画
                        rotate.setInterpolator(new LinearInterpolator());//设置为线性旋转
                        rotate.setFillAfter(true);
                        iv_ii_arrow.startAnimation(rotate);
                    }
                }
                break;
            case 2: //库存查询
                if(menu_index != 2){
                    rl_cashier.setBackgroundColor(getResources().getColor(R.color.white));
                    view_cashier_selected.setVisibility(View.GONE);
                    tv_cashier.setTextColor(getResources().getColor(R.color.six_six));
                    rl_inventory_inquiry.setBackgroundColor(getResources().getColor(R.color.three_f5));
                    view_ii_selected.setVisibility(View.VISIBLE);
                    tv_ii.setTextColor(getResources().getColor(R.color.main_blue));
                    ll_ii_menus.setVisibility(View.VISIBLE);
                    rl_backstage_management.setBackgroundColor(getResources().getColor(R.color.white));
                    view_back_selected.setVisibility(View.GONE);
                    tv_back_manage.setTextColor(getResources().getColor(R.color.six_six));
                    ll_bm_menus.setVisibility(View.GONE);
                    if(menu_index == 5){
                        Animation rotate = AnimationUtils.loadAnimation(activity, R.anim.sanim_arrow_back);//创建动画
                        rotate.setInterpolator(new LinearInterpolator());//设置为线性旋转
                        rotate.setFillAfter(true);
                        iv_bm_arrow.startAnimation(rotate);
                    }
                }
                break;
            case 3: //库存查询-商品入库
                view_cs.setBackgroundResource(R.drawable.sshape_menu_point_selected);
                tv_cs.setTextColor(getResources().getColor(R.color.main_blue));
                view_or.setBackgroundResource(R.drawable.sshape_menu_point_normal);
                tv_or.setTextColor(getResources().getColor(R.color.six_six));
                break;
            case 4: //库存查询-操作记录
                view_cs.setBackgroundResource(R.drawable.sshape_menu_point_normal);
                tv_cs.setTextColor(getResources().getColor(R.color.six_six));
                view_or.setBackgroundResource(R.drawable.sshape_menu_point_selected);
                tv_or.setTextColor(getResources().getColor(R.color.main_blue));
                break;
            case 5: //后台管理
                if(menu_index != 5){
                    rl_cashier.setBackgroundColor(getResources().getColor(R.color.white));
                    view_cashier_selected.setVisibility(View.GONE);
                    tv_cashier.setTextColor(getResources().getColor(R.color.six_six));
                    rl_inventory_inquiry.setBackgroundColor(getResources().getColor(R.color.white));
                    view_ii_selected.setVisibility(View.GONE);
                    tv_ii.setTextColor(getResources().getColor(R.color.six_six));
                    tv_cs.setTextColor(getResources().getColor(R.color.six_six));
                    view_cs.setBackgroundResource(R.drawable.sshape_menu_point_normal);
                    tv_or.setTextColor(getResources().getColor(R.color.six_six));
                    view_or.setBackgroundResource(R.drawable.sshape_menu_point_normal);
                    ll_ii_menus.setVisibility(View.GONE);
                    rl_backstage_management.setBackgroundColor(getResources().getColor(R.color.three_f5));
                    view_back_selected.setVisibility(View.VISIBLE);
                    tv_back_manage.setTextColor(getResources().getColor(R.color.main_blue));
                    ll_bm_menus.setVisibility(View.VISIBLE);
                    if(menu_index == 2 || menu_index == 3 || menu_index == 4){
                        Animation rotate = AnimationUtils.loadAnimation(activity, R.anim.sanim_arrow_back);//创建动画
                        rotate.setInterpolator(new LinearInterpolator());//设置为线性旋转
                        rotate.setFillAfter(true);
                        iv_ii_arrow.startAnimation(rotate);
                    }
                }
                break;
        }
    }

    //默认是收银台界面
    private void initFragment(){
        nowFragment = CashierHomeFragment.getInstance();
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.frame_main,nowFragment).commit();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if(id == R.id.rl_cashier){ //收银台
            if(pCashier){
                resetGmMenus();
                changeMenuState(1);
                changeFragment(nowFragment,CashierHomeFragment.getInstance());
                CashierHomeFragment.getInstance().initTypeList();
                if(menu_index != 1){
                    menu_index = 1;
                }
            }else{
                SDToast.showToast(context,"无收银台权限");
            }
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.rl_inventory_inquiry){ //库存查询
            resetGmMenus();
            changeMenuState(2);
            if(menu_index != 2){
                Animation rotate = AnimationUtils.loadAnimation(activity, R.anim.sanim_arrow);//创建动画
                rotate.setInterpolator(new LinearInterpolator());//设置为线性旋转
                rotate.setFillAfter(true);
                iv_ii_arrow.startAnimation(rotate);
                menu_index = 2;
            }
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.rl_cs){ //库存查询-商品入库
            if(pStorage){
                changeMenuState(3);
                changeFragment(nowFragment, CommodityStorageFragment.getInstance());
            }else{
                SDToast.showToast(context,"无商品入库权限");
            }
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.rl_or){ //库存查询-操作记录
            if(pOperateRecord){
                changeFragment(nowFragment, OperationRecordFragment.getInstance());
                changeMenuState(4);
            }else{
                SDToast.showToast(context,"无操作记录权限");
            }
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.rl_backstage_management){ //后台管理
            changeMenuState(5);
            if(menu_index != 5){
                Animation rotate = AnimationUtils.loadAnimation(activity, R.anim.sanim_arrow);//创建动画
                rotate.setInterpolator(new LinearInterpolator());//设置为线性旋转
                rotate.setFillAfter(true);
                iv_bm_arrow.startAnimation(rotate);
                menu_index = 5;
            }
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.rl_gm){ //后台管理-商品管理
            if(pGoodManage){
                choseGmMenu(1);
                changeFragment(nowFragment, BackstageGoodsManageFragment.getInstance());
            }else{
                SDToast.showToast(context,"无商品管理权限");
            }
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.rl_um){ //后台管理-用户管理
            if(pUserManage){
                choseGmMenu(2);
                changeFragment(nowFragment, UserManageFragment.getInstance());
            }else{
                SDToast.showToast(context,"无用户管理权限");
            }
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.rl_mm){ //后台管理-会员管理
            choseGmMenu(3);
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.rl_bi){ //后台管理-商家资料
            choseGmMenu(4);
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.rl_cash_permission){ //后台管理-收银权限
            if(pCashPermission){
                choseGmMenu(5);
                changeFragment(nowFragment, CashPermissionFragment.getInstance());
            }else{
                SDToast.showToast(context,"无收银权限权限");
            }
            KeyboardUtil.hideSoftInput(activity);
        }else if(id == R.id.tv_loginout){
            LocalUserModelDao.deleteAllModel();
            MenuModelDao.deleteAllModel();
            StoreBeanDao.deleteAllModel();
            finish();
        }else if(id == R.id.ll_change_location){ //切换门店
            List<StoreBean> storeBeanList = StoreBeanDao.queryModel();
            if(storeBeanList != null && storeBeanList.size() > 0){
                //选择门店
                rv_popup.setAdapter(storeBeanAdapter);
                storeBeanAdapter.setDatas(storeBeanList);
                showItemsPopup();
            }
        }else if(id == R.id.view_mask){
            hideItemsPopup();
        }
    }

    public void showItemsPopup(){
        if(rl_popup_items.getVisibility() == View.GONE){
            rl_popup_items.startAnimation(AnimationUtil.getMaskViewAppearAnim());
            rl_popup_items.setVisibility(View.VISIBLE);
        }
        showViewMask();
    }

    private void hideItemsPopup(){
        if(rl_popup_items.getVisibility() == View.VISIBLE){
            rl_popup_items.startAnimation(AnimationUtil.getMaskViewDisappearAnim());
            rl_popup_items.setVisibility(View.GONE);
        }
        hideViewMask();
    }

    private void hideViewMask(){
        view_mask.startAnimation(AnimationUtil.getMaskViewDisappearAnim());
        view_mask.setVisibility(View.GONE);
    }

    private void showViewMask(){
        view_mask.startAnimation(AnimationUtil.getMaskViewAppearAnim());
        view_mask.setVisibility(View.VISIBLE);
    }

    public String getLocationId(){
        return locationId;
    }

    public String getSupplierId(){
        return supplierId;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }

    @Override
    public void onBackPressed() {

    }

    /** 保存MyTouchListener接口的列表 */
    private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<>();

    /** 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法 */
    public void registerMyTouchListener(MyTouchListener listener) {
        myTouchListeners.add(listener);
    }

    /** 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法 */
    public void unRegisterMyTouchListener(MyTouchListener listener) {
        myTouchListeners.remove( listener );
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (MyTouchListener listener : myTouchListeners) {
            listener.onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public interface MyTouchListener {
        /** onTOuchEvent的实现 */
        boolean onTouchEvent(MotionEvent event);
    }

}
